import { action, computed, observable } from 'mobx';

class AppleStore {
  @observable apples = [];
  @observable newAppleId = 0;
  @observable buttonText = '摘苹果';
  @observable isPicking = false;

  @computed get curAppleCount () {
    return this.apples.filter(apple => !apple.isEaten).length;
  }

  @computed get curAppleWeight () {
    return this.apples.reduce((total, apple) => {
      if (!apple.isEaten) {
        total += apple.weight;
      }
      return total;
    }, 0);
  }

  @computed get eatenAppleCount () {
    return this.apples.filter(apple => apple.isEaten).length;
  }

  @computed get eatenAppleWeight () {
    return this.apples.reduce((total, apple) => {
      if (apple.isEaten) {
        total += apple.weight;
      }
      return total;
    }, 0);
  }

  @action.bound pickApple () {
    if (this.isPicking) {
      return;
    }
    this.isPicking = true;
    this.buttonText = '正在采摘';
    fetch('https://hacker-news.firebaseio.com/v0/jobstories.json').then(res => {
      this.apples.push({
        id: this.newAppleId++,
        weight: Math.floor(200 + Math.random() * 50),
        isEaten: false
      });
      this.isPicking = false;
      this.buttonText = '摘苹果';
    });
  }

  @action.bound eatApple (appleId) {
    const apple = this.apples.find(apple => apple.id === appleId);
    apple.isEaten = true;
  }
  
}

const appleStore = new AppleStore();

export default appleStore;

